<!DOCTYPE html>





<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 3.9.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico?v=7.4.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=7.4.0">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico?v=7.4.0">
  <link rel="mask-icon" href="/images/logo.svg?v=7.4.0" color="#222">

<link rel="stylesheet" href="/css/main.css?v=7.4.0">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.4.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.json',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    },
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="Nginx功能丰富，可作为HTTP服务器，也可作为反向代理服务器，邮件服务器。支持FastCGI、SSL、Virtual Host、URL Rewrite、Gzip等功能。并且支持很多第三方的模块扩展。 零. 前言0.1 配置文件在哪安装好nginx我们首先要知道配置文件在哪里?  说明nginx的主配置文件都在 /etc/nginx/nginx.conf里. 打开文件我们还可以看到 12incl">
<meta name="keywords" content="linux,nginx">
<meta property="og:type" content="article">
<meta property="og:title" content="nginx介绍和常用模块配置">
<meta property="og:url" content="https://unix2dos.github.io/p/7245bfc7.html">
<meta property="og:site_name" content="Levon&#39;s Blog">
<meta property="og:description" content="Nginx功能丰富，可作为HTTP服务器，也可作为反向代理服务器，邮件服务器。支持FastCGI、SSL、Virtual Host、URL Rewrite、Gzip等功能。并且支持很多第三方的模块扩展。 零. 前言0.1 配置文件在哪安装好nginx我们首先要知道配置文件在哪里?  说明nginx的主配置文件都在 /etc/nginx/nginx.conf里. 打开文件我们还可以看到 12incl">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://unix2dos.github.io/p/7245bfc7/1.png">
<meta property="og:image" content="https://unix2dos.github.io/p/7245bfc7/1.jpg">
<meta property="og:image" content="https://unix2dos.github.io/p/7245bfc7/2.jpg">
<meta property="og:image" content="https://unix2dos.github.io/p/7245bfc7/3.jpg">
<meta property="og:updated_time" content="2019-09-27T15:36:51.166Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="nginx介绍和常用模块配置">
<meta name="twitter:description" content="Nginx功能丰富，可作为HTTP服务器，也可作为反向代理服务器，邮件服务器。支持FastCGI、SSL、Virtual Host、URL Rewrite、Gzip等功能。并且支持很多第三方的模块扩展。 零. 前言0.1 配置文件在哪安装好nginx我们首先要知道配置文件在哪里?  说明nginx的主配置文件都在 /etc/nginx/nginx.conf里. 打开文件我们还可以看到 12incl">
<meta name="twitter:image" content="https://unix2dos.github.io/p/7245bfc7/1.png">
  <link rel="canonical" href="https://unix2dos.github.io/p/7245bfc7">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>nginx介绍和常用模块配置 | Levon's Blog</title>
  








  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">
  <div class="container use-motion">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Levon's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <h1 class="site-subtitle" itemprop="description">微信:  L6241425</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
      
      
      
        
        <li class="menu-item menu-item-home">
      
    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-archives">
      
    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>时光</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-categories">
      
    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-tags">
      
    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
      <li class="menu-item menu-item-search">
        <a href="javascript:;" class="popup-trigger">
        
          <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
      </li>
    
  </ul>

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="none"
           placeholder="搜索..." spellcheck="false"
           type="text" id="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result"></div>

</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
            

          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
      <article itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block post">
    <link itemprop="mainEntityOfPage" href="https://unix2dos.github.io/p/7245bfc7.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Levon">
      <meta itemprop="description" content="Never Give Up">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Levon's Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">nginx介绍和常用模块配置

          
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              
                
              

              <time title="创建时间：2019-07-07 23:54:46" itemprop="dateCreated datePublished" datetime="2019-07-07T23:54:46+08:00">2019-07-07</time>
            </span>
          
            

            
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2019-09-27 23:36:51" itemprop="dateModified" datetime="2019-09-27T23:36:51+08:00">2019-09-27</time>
              </span>
            
          
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/2-linux系统/" itemprop="url" rel="index"><span itemprop="name">2-linux系统</span></a></span>

                
                
                  ，
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/2-linux系统/nginx/" itemprop="url" rel="index"><span itemprop="name">nginx</span></a></span>

                
                
              
            </span>
          

          
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
        
      
      <span class="post-meta-item-text">Disqus：</span>
    
    <a title="disqus" href="/p/7245bfc7.html#comments" itemprop="discussionUrl"><span class="post-comments-count disqus-comment-count" data-disqus-identifier="p/7245bfc7.html" itemprop="commentCount"></span></a>
  </span>
  
  
          <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
              
                <span class="post-meta-item-text">本文字数：</span>
              
              <span>13k</span>
            </span>
          
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
              
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              
              <span>12 分钟</span>
            </span>
          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>Nginx功能丰富，可作为HTTP服务器，也可作为反向代理服务器，邮件服务器。支持FastCGI、SSL、Virtual Host、URL Rewrite、Gzip等功能。并且支持很多第三方的模块扩展。</p>
<h1 id="零-前言"><a href="#零-前言" class="headerlink" title="零. 前言"></a>零. 前言</h1><h3 id="0-1-配置文件在哪"><a href="#0-1-配置文件在哪" class="headerlink" title="0.1 配置文件在哪"></a>0.1 配置文件在哪</h3><p>安装好nginx我们首先要知道配置文件在哪里?</p>
<p><img src="/p/7245bfc7/1.png" alt="1"></p>
<p>说明nginx的主配置文件都在 <code>/etc/nginx/nginx.conf</code>里. 打开文件我们还可以看到</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">include /etc/nginx/conf.d/*.conf;</span><br><span class="line">include /etc/nginx/sites-enabled/*;</span><br></pre></td></tr></table></figure>

<p>需要添加新配置选项的地方位于 sites-enabled 文件夹。如果你打开这个文件夹，你会发现一个名为 default 的文档，打开后你就会找到nginx的配置选项, 当你安装好nginx默认看到的首页就是在这里配置的.</p>
<p>在该目录下还有一个 sites-available 的文件夹, 这个文件夹一般在你需要建立和管理多个站点的时候非常有用，可以帮助你更好的组织不同的项目。你需要在这里添加你的nginx配置文案并将他们链接至 sites-enabled 目录下。</p>
<p>只有在 sites-enabled 目录下的配置文件才能够真正被用户访问。但是你同样可以将文件放在 sites-available 目录下用来存档或者生成链接。</p>
<a id="more"></a>



<h3 id="0-2-默认root在哪"><a href="#0-2-默认root在哪" class="headerlink" title="0.2 默认root在哪"></a>0.2 默认root在哪</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">nginx -V</span><br><span class="line">it lists --prefix as the first one.</span><br></pre></td></tr></table></figure>

<h3 id="0-3-重启nginx"><a href="#0-3-重启nginx" class="headerlink" title="0.3 重启nginx"></a>0.3 重启nginx</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sudo nginx -s reload</span><br></pre></td></tr></table></figure>

<p>reload，重新加载的意思，reload会重新加载配置文件，nginx服务不会中断，而且reload时会测试conf语法等，如果出错会rollback用上一次正确配置文件保持正常运行。</p>
<p>restart，重启，会重启nginx服务。这个重启会造成服务一瞬间的中断，当然如果配置文件出错会导致服务启动失败，那就是更长时间的服务中断了。</p>
<h1 id="一-nginx-常用功能说明"><a href="#一-nginx-常用功能说明" class="headerlink" title="一. nginx 常用功能说明"></a>一. nginx 常用功能说明</h1><h3 id="1-1-反向代理"><a href="#1-1-反向代理" class="headerlink" title="1.1 反向代理"></a>1.1 反向代理</h3><p>下面一张图是对正向代理与反响代理的对比</p>
<p><img src="/p/7245bfc7/1.jpg" alt="1"></p>
<p>Nginx在做反向代理时，提供性能稳定，并且能够提供配置灵活的转发功能。Nginx可以根据不同的正则匹配，采取不同的转发策略，比如图片文件结尾的走文件服务器，动态页面走web服务器，只要你正则写的没问题，又有相对应的服务器解决方案，你就可以随心所欲的玩。并且Nginx对返回结果进行错误页跳转，异常判断等。如果被分发的服务器存在异常，他可以将请求重新转发给另外一台服务器，然后自动去除异常服务器。</p>
<h3 id="1-2-负载均衡"><a href="#1-2-负载均衡" class="headerlink" title="1.2 负载均衡"></a>1.2 负载均衡</h3><p>Nginx提供的负载均衡策略有2种：内置策略和扩展策略。</p>
<p>内置策略为轮询，加权轮询，Ip hash。扩展策略，就天马行空，只有你想不到的没有他做不到的啦，你可以参照所有的负载均衡算法，给他一一找出来做下实现。</p>
<p>看下面的图理解三种负载均衡算法的实现</p>
<p><img src="/p/7245bfc7/2.jpg" alt="1"></p>
<p>Ip hash算法，对客户端请求的ip进行hash操作，然后根据hash结果将同一个客户端ip的请求分发给同一台服务器进行处理，可以解决session不共享的问题。</p>
<p><img src="/p/7245bfc7/3.jpg" alt="1"></p>
<h3 id="1-3-web缓存"><a href="#1-3-web缓存" class="headerlink" title="1.3 web缓存"></a>1.3 web缓存</h3><p>nginx可以对不同的文件做不同的缓存处理，配置灵活，并且支持FastCGI_Cache，主要用于对FastCGI的动态程序进行缓存。配合着第三方的ngx_cache_purge，对制定的URL缓存内容可以的进行增删管理。</p>
<h1 id="二-nginx配置文件结构"><a href="#二-nginx配置文件结构" class="headerlink" title="二. nginx配置文件结构"></a>二. nginx配置文件结构</h1><p>先放一个配置demo</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">user</span>  nobody;</span><br><span class="line"><span class="attribute">worker_processes</span>  <span class="number">1</span>;</span><br><span class="line"><span class="attribute">pid</span>        logs/nginx.pid;</span><br><span class="line"></span><br><span class="line"><span class="section">events</span> &#123;</span><br><span class="line">    <span class="attribute">worker_connections</span>  <span class="number">1024</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="attribute">upstream</span> mysvr &#123;   </span><br><span class="line">  <span class="attribute">server</span> <span class="number">127.0.0.1:7878</span>;</span><br><span class="line">  <span class="attribute">server</span> <span class="number">192.168.10.121:3333</span> backup;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="section">http</span> &#123;</span><br><span class="line">    <span class="attribute">include</span>       mime.types;</span><br><span class="line">    <span class="attribute">default_type</span>  application/octet-stream;</span><br><span class="line">  </span><br><span class="line">    <span class="section">server</span> &#123;</span><br><span class="line">        <span class="attribute">listen</span>       <span class="number">80</span>;</span><br><span class="line">        <span class="attribute">server_name</span>  localhost;</span><br><span class="line">        <span class="attribute">location</span> / &#123;</span><br><span class="line">            <span class="attribute">root</span>   html;</span><br><span class="line">            <span class="attribute">index</span>  index.html index.htm;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="2-1-配置文件结构"><a href="#2-1-配置文件结构" class="headerlink" title="2.1 配置文件结构"></a>2.1 配置文件结构</h3><ul>
<li><p>main(全局块)[一个]</p>
</li>
<li><p>events (nginx工作模式)[一个]</p>
</li>
<li><p>http(http设置)[一个]</p>
<ul>
<li>server(主机设置)[http里多个]<ul>
<li>location(URL匹配)[server里多个]</li>
</ul>
</li>
<li>upstream(负载均衡服务器设置)[http里一个]</li>
</ul>
</li>
</ul>
<p>1、全局块：配置影响nginx全局的指令。一般有运行nginx服务器的用户组，nginx进程pid存放路径，日志存放路径，配置文件引入，允许生成worker process数等。</p>
<p>2、events块：配置影响nginx服务器或与用户的网络连接。有每个进程的最大连接数，选取哪种事件驱动模型处理连接请求，是否允许同时接受多个网路连接，开启多个网络连接序列化等。</p>
<p>3、http块：可以嵌套多个server，配置代理，缓存，日志定义等绝大多数功能和第三方模块的配置。如文件引入，mime-type定义，日志自定义，是否使用sendfile传输文件，连接超时时间，单连接请求数等。</p>
<p>4、server块：配置虚拟主机的相关参数，一个http中可以有多个server。</p>
<p>5、location块：配置请求的路由，以及各种页面的处理情况。</p>
<p>6、upstream块：负责负载均衡</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">########### 每个指令必须有分号结束。#################</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#user administrator administrators;  #配置用户或者组，默认为nobody nobody。</span></span><br><span class="line"><span class="comment">#worker_processes 2;  #允许生成的进程数，默认为1</span></span><br><span class="line"><span class="comment">#pid /nginx/pid/nginx.pid;   #指定nginx进程运行文件存放地址</span></span><br><span class="line"></span><br><span class="line"><span class="attribute">error_log</span> log/error.log <span class="literal">debug</span>;  <span class="comment">#制定日志路径，级别。这个设置可以放入全局块，http块，server块，级别分别为：debug|info|notice|warn|error|crit|alert|emerg</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="section">events</span> &#123;</span><br><span class="line">    <span class="attribute">accept_mutex</span> <span class="literal">on</span>;   <span class="comment">#设置网路连接序列化，防止惊群现象发生，默认为on</span></span><br><span class="line">    <span class="attribute">multi_accept</span> <span class="literal">on</span>;  <span class="comment">#设置一个进程是否同时接受多个网络连接，默认为off</span></span><br><span class="line">    <span class="comment">#use epoll;      #事件驱动模型，select|poll|kqueue|epoll|resig|/dev/poll|eventport</span></span><br><span class="line">    <span class="attribute">worker_connections</span>  <span class="number">1024</span>;    <span class="comment">#最大连接数，默认为512</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="section">http</span> &#123;</span><br><span class="line">    <span class="attribute">include</span>       mime.types;   <span class="comment">#文件扩展名与文件类型映射表</span></span><br><span class="line">    <span class="attribute">default_type</span>  application/octet-stream; <span class="comment">#默认文件类型，默认为text/plain</span></span><br><span class="line">    <span class="comment">#access_log off; #取消服务日志    </span></span><br><span class="line">    <span class="attribute">log_format</span> myFormat <span class="string">'<span class="variable">$remote_addr</span>–<span class="variable">$remote_user</span> [<span class="variable">$time_local</span>] <span class="variable">$request</span> <span class="variable">$status</span> <span class="variable">$body_bytes_sent</span> <span class="variable">$http_referer</span> <span class="variable">$http_user_agent</span> <span class="variable">$http_x_forwarded_for</span>'</span>; <span class="comment">#自定义格式</span></span><br><span class="line">    <span class="attribute">access_log</span> log/access.log myFormat;  <span class="comment">#combined为日志格式的默认值</span></span><br><span class="line">  </span><br><span class="line"> </span><br><span class="line">    <span class="attribute">sendfile</span> <span class="literal">on</span>;   <span class="comment">#允许sendfile方式传输文件，默认为off，可以在http块，server块，location块。</span></span><br><span class="line">    <span class="attribute">sendfile_max_chunk</span> <span class="number">100k</span>;  <span class="comment">#每个进程每次调用传输数量不能大于设定的值，默认为0，即不设上限。</span></span><br><span class="line">    <span class="attribute">keepalive_timeout</span> <span class="number">65</span>;  <span class="comment">#连接超时时间，默认为75s，可以在http，server，location块。</span></span><br><span class="line"></span><br><span class="line">    <span class="attribute">upstream</span> mysvr &#123;   </span><br><span class="line">      <span class="attribute">server</span> <span class="number">127.0.0.1:7878</span>;</span><br><span class="line">      <span class="attribute">server</span> <span class="number">192.168.10.121:3333</span> backup;  <span class="comment">#热备</span></span><br><span class="line">    &#125;</span><br><span class="line">  </span><br><span class="line">    <span class="attribute">error_page</span> <span class="number">404</span> https://www.baidu.com; <span class="comment">#错误页</span></span><br><span class="line">    </span><br><span class="line">  	<span class="section">server</span> &#123;</span><br><span class="line">        <span class="attribute">keepalive_requests</span> <span class="number">120</span>; <span class="comment">#单连接请求上限次数。</span></span><br><span class="line">        <span class="attribute">listen</span>       <span class="number">4545</span>;   <span class="comment">#监听端口</span></span><br><span class="line">        <span class="attribute">server_name</span>  <span class="number">127.0.0.1</span>;   <span class="comment">#监听地址       </span></span><br><span class="line">        </span><br><span class="line">    		<span class="attribute">location</span>  ~*^.+$ &#123;       <span class="comment">#请求的url过滤，正则匹配，~为区分大小写，~*为不区分大小写。</span></span><br><span class="line">           <span class="comment">#root path;  #根目录</span></span><br><span class="line">           <span class="comment">#index vv.txt;  #设置默认页</span></span><br><span class="line">           <span class="attribute">proxy_pass</span>  http://mysvr;  <span class="comment">#请求转向mysvr 定义的服务器列表</span></span><br><span class="line">           <span class="attribute">deny</span> <span class="number">127.0.0.1</span>;  <span class="comment">#拒绝的ip</span></span><br><span class="line">           <span class="attribute">allow</span> <span class="number">172.18.5.54</span>; <span class="comment">#允许的ip           </span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><p><code>$remote_addr</code> 与<code>$http_x_forwarded_for</code> 用以记录客户端的ip地址； </p>
</li>
<li><p><code>$remote_user</code> 用来记录客户端用户名称； </p>
</li>
<li><p><code>$time_local</code> 用来记录访问时间与时区；</p>
</li>
<li><p><code>$request</code> 用来记录请求的url与http协议；</p>
</li>
<li><p><code>$status</code> 用来记录请求状态；成功是200， </p>
</li>
<li><p><code>body_bytes_sent</code> 记录发送给客户端文件主体内容大小；</p>
</li>
<li><p><code>$http_referer</code> 用来记录从那个页面链接访问过来的； 8.$http_user_agent ：记录客户端浏览器的相关信息；</p>
</li>
<li><p>惊群现象：一个网路连接到来，多个睡眠的进程被同时叫醒，但只有一个进程能获得链接，这样会影响系统性能。</p>
</li>
<li><p>每个指令必须有分号结束。</p>
</li>
</ul>
<h1 id="三-模块配置说明"><a href="#三-模块配置说明" class="headerlink" title="三. 模块配置说明"></a>三. 模块配置说明</h1><h3 id="3-1-main模块"><a href="#3-1-main模块" class="headerlink" title="3.1 main模块"></a>3.1 main模块</h3><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">user</span> nobody nobody;</span><br><span class="line"><span class="attribute">worker_processes</span> <span class="number">2</span>;</span><br><span class="line"><span class="attribute">error_log</span>  /usr/local/var/log/nginx/error.log  <span class="literal">notice</span>;</span><br><span class="line"><span class="attribute">pid</span>        /usr/local/var/run/nginx/nginx.pid;</span><br><span class="line"><span class="attribute">worker_rlimit_nofile</span> <span class="number">1024</span>;</span><br></pre></td></tr></table></figure>

<ul>
<li><p>user 来指定Nginx Worker进程运行用户以及用户组，默认由nobody账号运行。</p>
</li>
<li><p>worker_processes来指定了Nginx要开启的子进程数。每个Nginx进程平均耗费10M~12M内存。根据经验，一般指定1个进程就足够了，如果是多核CPU，建议指定和CPU的数量一样的进程数即可。我这里写2，那么就会开启2个子进程，总共3个进程。可以写 auto.</p>
</li>
<li><p>error_log用来定义全局错误日志文件。日志输出级别有debug、info、notice、warn、error、crit可供选择，其中，debug输出日志最为最详细，而crit输出日志最少。</p>
</li>
<li><p>pid用来指定进程id的存储文件位置。</p>
</li>
<li><p>worker_rlimit_nofile用于指定一个nginx进程可以打开的最多文件描述符数目，这里是65535，需要使用命令“ulimit -n 65535”来设置。</p>
</li>
</ul>
<h3 id="3-2-events-模块"><a href="#3-2-events-模块" class="headerlink" title="3.2 events 模块"></a>3.2 events 模块</h3><p>events模块来用指定nginx的工作模式和工作模式及连接数上限</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="section">events</span> &#123;</span><br><span class="line">     <span class="attribute">use</span> <span class="literal">kqueue</span>; <span class="comment">#mac平台</span></span><br><span class="line">     <span class="attribute">worker_connections</span>  <span class="number">1024</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><p>use用来指定Nginx的工作模式。Nginx支持的工作模式有select、poll、kqueue、epoll、rtsig和/dev/poll。其中select和poll都是标准的工作模式，kqueue和epoll是高效的工作模式，不同的是epoll用在Linux平台上，而kqueue用在BSD系统中，因为Mac基于BSD,所以Mac也得用这个模式，对于Linux系统，epoll工作模式是首选。</p>
</li>
<li><p>worker_connections用于定义Nginx每个进程的最大连接数，即接收前端的最大请求数，默认是1024。最大客户端连接数由worker_processes和worker_connections决定</p>
</li>
<li><p>即Max_clients=worker_processes*worker_connections，在作为反向代理时，Max_clients变为：Max_clients = worker_processes * worker_connections/4。 </p>
</li>
<li><p>进程的最大连接数受Linux系统进程的最大打开文件数限制，在执行操作系统命令“ulimit -n 65536”后worker_connections的设置才能生效。</p>
</li>
</ul>
<h3 id="3-3-http-模块"><a href="#3-3-http-模块" class="headerlink" title="3.3 http 模块"></a>3.3 http 模块</h3><p>http模块可以说是最核心的模块了，它负责HTTP服务器相关属性的配置，它里面的server和upstream子模块，至关重要。</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="section">http</span> &#123;</span><br><span class="line">     <span class="attribute">include</span>       mime.types;</span><br><span class="line">     <span class="attribute">default_type</span>  application/octet-stream;</span><br><span class="line">     <span class="attribute">log_format</span>  main  <span class="string">'remote_addr - remote_user [time_local] "request" '</span></span><br><span class="line">                       <span class="string">'status body_bytes_sent "<span class="variable">$http_referer</span>" '</span></span><br><span class="line">                       <span class="string">'"http_user_agent" "http_x_forwarded_for"'</span>;</span><br><span class="line">     <span class="attribute">access_log</span>  /usr/local/var/log/nginx/access.log  main;</span><br><span class="line">     <span class="attribute">sendfile</span>        <span class="literal">on</span>;</span><br><span class="line">     <span class="attribute">tcp_nopush</span>      <span class="literal">on</span>;</span><br><span class="line">     <span class="attribute">tcp_nodelay</span>     <span class="literal">on</span>;</span><br><span class="line">     <span class="attribute">keepalive_timeout</span>  <span class="number">10</span>;</span><br><span class="line">     <span class="comment">#gzip  on;</span></span><br><span class="line">     </span><br><span class="line">     <span class="attribute">upstream</span> myproject &#123;</span><br><span class="line">         .....</span><br><span class="line">     &#125;</span><br><span class="line">     </span><br><span class="line">  	 <span class="section">server</span> &#123;</span><br><span class="line">         ....</span><br><span class="line">     &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><p>include 用来设定文件的mime类型,类型在配置文件目录下的mime.type文件定义，来告诉nginx来识别文件类型。</p>
</li>
<li><p>default_type设定了默认的类型为二进制流，也就是当文件类型未定义时使用这种方式。</p>
</li>
<li><p>log_format用于设置日志的格式，和记录哪些参数，这里设置为main，刚好用于access_log来记录这种类型。</p>
<p>main的类型日志如下：也可以增删部分参数。</p>
<p>127.0.0.1 - - [21/Apr/2015:18:09:54 +0800] “GET /index.php HTTP/1.1” 200 87151 “-“ “Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.76 Safari/537.36” </p>
</li>
<li><p>access_log 用来纪录每次的访问日志的文件地址，后面的main是日志的格式样式，对应于log_format的main。</p>
</li>
<li><p>sendfile参数用于开启高效文件传输模式。</p>
</li>
<li><p>将tcp_nopush和tcp_nodelay两个指令设置为on用于防止网络阻塞。</p>
</li>
<li><p>keepalive_timeout设置客户端连接保持活动的超时时间。在超过这个时间之后，服务器会关闭该连接。</p>
</li>
</ul>
<h3 id="3-4-server-模块-http的子模块-虚拟主机"><a href="#3-4-server-模块-http的子模块-虚拟主机" class="headerlink" title="3.4 server 模块 (http的子模块, 虚拟主机)"></a>3.4 server 模块 (http的子模块, 虚拟主机)</h3><p>sever 模块是http的子模块，它用来定一个虚拟主机。我们看一下一个简单的server 是如何做的？</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="section">server</span> &#123;</span><br><span class="line">         <span class="attribute">listen</span>       <span class="number">8080</span>;</span><br><span class="line">         <span class="attribute">server_name</span>  test.liuvv.com;</span><br><span class="line">         <span class="attribute">root</span>   /home/levonfly/www;         <span class="comment"># 全局定义，如果都是这一个目录，这样定义最简单。</span></span><br><span class="line">         <span class="attribute">index</span>  index.php index.html index.htm; </span><br><span class="line">         <span class="attribute">charset</span> utf-<span class="number">8</span>;</span><br><span class="line">         <span class="attribute">access_log</span>  usr/local/var/log/host.access.log  main;</span><br><span class="line">         <span class="attribute">aerror_log</span>  usr/local/var/log/host.<span class="literal">error</span>.log  <span class="literal">error</span>;</span><br><span class="line">         ....</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><p>server标志定义虚拟主机开始。 </p>
</li>
<li><p>listen用于指定虚拟主机的服务端口。 </p>
</li>
<li><p>server_name用来指定IP地址或者域名，多个域名之间用空格分开。 </p>
</li>
<li><p>root 表示在这整个server虚拟主机内，全部的root web根目录。注意要和locate {}下面定义的区分开来。 </p>
</li>
<li><p>index 全局定义访问的默认首页地址。注意要和locate {}下面定义的区分开来。 </p>
</li>
<li><p>charset用于设置网页的默认编码格式。 </p>
</li>
<li><p>access_log用来指定此虚拟主机的访问日志存放路径，最后的main用于指定访问日志的输出格式。</p>
</li>
</ul>
<h3 id="3-5-location-模块-server的子模块-重要"><a href="#3-5-location-模块-server的子模块-重要" class="headerlink" title="3.5 location 模块(server的子模块, 重要)"></a>3.5 location 模块(server的子模块, 重要)</h3><p>location模块是nginx中用的最多的，也是最重要的模块了，什么负载均衡啊、反向代理啊、虚拟域名啊都与它相关。</p>
<p>location 根据它字面意思就知道是来定位的，定位URL，解析URL，所以，它也提供了强大的正则匹配功能，也支持条件判断匹配，用户可以通过location指令实现Nginx对动、静态网页进行过滤处理。</p>
<p>我们先来看这个，设定默认首页和虚拟机目录。</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">location</span> / &#123;</span><br><span class="line">	<span class="attribute">root</span>   /home/levonfly/www;</span><br><span class="line">	<span class="attribute">index</span>  index.php index.html index.htm;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><p>location /表示匹配访问根目录。</p>
</li>
<li><p>root指令用于指定访问根目录时，虚拟主机的web目录，这个目录可以是相对路径（相对路径是相对于nginx的安装目录）。也可以是绝对路径。</p>
</li>
<li><p>index用于设定我们只输入域名后访问的默认首页地址，有个先后顺序：index.php index.html index.htm，如果没有开启目录浏览权限，又找不到这些默认首页，就会报403错误。</p>
</li>
</ul>
<p>location 还有一种方式就是正则匹配，开启正则匹配这样：<code>location ~</code>。后面加个<code>~</code>。下面这个例子是运用<code>正则匹配</code>来链接php。</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">location</span> <span class="regexp">~ \.php$</span> &#123;</span><br><span class="line">            <span class="attribute">root</span>           /home/levonfly/www;</span><br><span class="line">            <span class="attribute">fastcgi_pass</span>   <span class="number">127.0.0.1:9000</span>;</span><br><span class="line">            <span class="attribute">fastcgi_index</span>  index.php;</span><br><span class="line">            <span class="attribute">include</span>        fastcgi.conf;</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure>

<p><code>\.php$</code> 熟悉正则的我们直到，这是匹配<code>.php</code>结尾的URL，用来解析php文件。里面的<code>root</code>也是一样，用来表示虚拟主机的根目录。<br><code>fast_pass</code>链接的是<code>php-fpm</code> 的地址，之前我们也搭建过。其他几个参数我们以后再说。</p>
<h3 id="3-6-upstream-模块-http子模块"><a href="#3-6-upstream-模块-http子模块" class="headerlink" title="3.6 upstream 模块(http子模块)"></a>3.6 upstream 模块(http子模块)</h3><p>upstream 模块负债负载均衡模块，通过一个简单的调度算法来实现客户端IP到后端服务器的负载均衡。我先学习怎么用，具体的使用实例以后再说。</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">upstream</span> liuvv.com&#123;</span><br><span class="line">     ip_hash;</span><br><span class="line">     <span class="attribute">server</span> <span class="number">192.168.12.1:80</span>;</span><br><span class="line">     <span class="attribute">server</span> <span class="number">192.168.12.2:80</span> down;</span><br><span class="line">     <span class="attribute">server</span> <span class="number">192.168.12.3:8080</span>  max_fails=<span class="number">3</span>  fail_timeout=<span class="number">20s</span>;</span><br><span class="line">     <span class="attribute">server</span> <span class="number">192.168.12.4:8080</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面的例子中，通过upstream指令指定了一个负载均衡器的名称liuvv.com。这个名称可以任意指定，在后面需要的地方直接调用即可。</p>
<p>里面是ip_hash这是其中的一种负载均衡调度算法，下面会着重介绍。紧接着就是各种服务器了。用server关键字表识，后面接ip。</p>
<p>Nginx的负载均衡模块目前支持4种调度算法:</p>
<ol>
<li>weight 轮询（默认）。每个请求按时间顺序逐一分配到不同的后端服务器，如果后端某台服务器宕机，故障系统被自动剔除，使用户访问不受影响。weight。指定轮询权值，weight值越大，分配到的访问机率越高，主要用于后端每个服务器性能不均的情况下。</li>
<li>ip_hash。每个请求按访问IP的hash结果分配，这样来自同一个IP的访客固定访问一个后端服务器，有效解决了动态网页存在的session共享问题。</li>
<li>fair。比上面两个更加智能的负载均衡算法。此种算法可以依据页面大小和加载时间长短智能地进行负载均衡，也就是根据后端服务器的响应时间来分配请求，响应时间短的优先分配。Nginx本身是不支持fair的，如果需要使用这种调度算法，必须下载Nginx的upstream_fair模块。</li>
<li>url_hash。按访问url的hash结果来分配请求，使每个url定向到同一个后端服务器，可以进一步提高后端缓存服务器的效率。Nginx本身是不支持url_hash的，如果需要使用这种调度算法，必须安装Nginx 的hash软件包。</li>
</ol>
<p>在HTTP Upstream模块中，可以通过server指令指定后端服务器的IP地址和端口，同时还可以设定每个后端服务器在负载均衡调度中的状态。常用的状态有：</p>
<ul>
<li>down，表示当前的server暂时不参与负载均衡。</li>
<li>backup，预留的备份机器。当其他所有的非backup机器出现故障或者忙的时候，才会请求backup机器，因此这台机器的压力最轻。</li>
<li>max_fails，允许请求失败的次数，默认为1。当超过最大次数时，返回proxy_next_upstream 模块定义的错误。</li>
<li>fail_timeout，在经历了max_fails次失败后，暂停服务的时间。max_fails可以和fail_timeout一起使用。</li>
</ul>
<p><strong>注意</strong> 当负载调度算法为ip_hash时，后端服务器在负载均衡调度中的状态不能是weight和backup。</p>
<h1 id="四-nginx-配置实战"><a href="#四-nginx-配置实战" class="headerlink" title="四. nginx 配置实战"></a>四. nginx 配置实战</h1><h3 id="4-1-nginx指令"><a href="#4-1-nginx指令" class="headerlink" title="4.1 nginx指令"></a>4.1 nginx指令</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">nginx -s signal</span><br></pre></td></tr></table></figure>

<p>Where <em>signal</em> may be one of the following:</p>
<ul>
<li>stop — fast shutdown</li>
<li>quit — graceful shutdown</li>
<li>reload — reloading the configuration file</li>
<li>reopen — reopening the log files</li>
</ul>
<h3 id="4-2-nginx-快速配置教程"><a href="#4-2-nginx-快速配置教程" class="headerlink" title="4.2 nginx 快速配置教程"></a>4.2 nginx 快速配置教程</h3><p><a href="https://nginx.org/en/docs/beginners_guide.html" target="_blank" rel="noopener">https://nginx.org/en/docs/beginners_guide.html</a></p>
<h5 id="4-2-1-如果有多个location模块-匹配最长的"><a href="#4-2-1-如果有多个location模块-匹配最长的" class="headerlink" title="4.2.1 如果有多个location模块, 匹配最长的"></a>4.2.1 如果有多个location模块, 匹配最长的</h5><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">location</span> / &#123;</span><br><span class="line">        <span class="attribute">root</span> /home/levonfly/www;	<span class="comment">#http://test.liuvv.com/</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="attribute">location</span> /images/ &#123; <span class="comment"># 路径是两者相加/home/levonfly/images/</span></span><br><span class="line">        <span class="attribute">root</span> /home/levonfly;	<span class="comment">#http://test.liuvv.com/images/1.png</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="4-2-2-一个nginx实例可以通过listen监听不同端口"><a href="#4-2-2-一个nginx实例可以通过listen监听不同端口" class="headerlink" title="4.2.2 一个nginx实例可以通过listen监听不同端口"></a>4.2.2 一个nginx实例可以通过listen监听不同端口</h5><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="section">server</span> &#123;</span><br><span class="line">    <span class="attribute">listen</span> <span class="number">8080</span>;</span><br><span class="line">    <span class="attribute">root</span> /home/levonfly/<span class="number">8080</span>;  <span class="comment"># location没有root, 就用这里的root, 继承关系</span></span><br><span class="line"></span><br><span class="line">    <span class="attribute">location</span> / &#123;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="section">server</span> &#123;</span><br><span class="line">        <span class="attribute">listen</span> <span class="number">80</span>;</span><br><span class="line">        <span class="attribute">server_name</span> <span class="regexp">*.liuvv.com</span>;</span><br><span class="line">        <span class="attribute">location</span> / &#123;</span><br><span class="line">                <span class="attribute">proxy_pass</span> http://localhost:8080;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="attribute">location</span> /images/ &#123;   </span><br><span class="line">                <span class="attribute">root</span> /home/levonfly/; <span class="comment"># http://test.liuvv.com/images/1.png</span></span><br><span class="line">        &#125;</span><br><span class="line">  </span><br><span class="line">  	    <span class="comment">#location ~ \.(gif|jpg|png)$ &#123;  # 1.判断后缀 2. 波浪线是正则</span></span><br><span class="line">        <span class="comment">#        root /home/levonfly/images; # http://test.liuvv.com/1.png</span></span><br><span class="line">        <span class="comment">#&#125;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="4-2-3-fastcgi方式"><a href="#4-2-3-fastcgi方式" class="headerlink" title="4.2.3 fastcgi方式"></a>4.2.3 fastcgi方式</h5><p>nginx本身不能处理php，它只是个web服务器，当接收到请求后，如果是php请求，则发给php解释器处理，并把结果返回给客户端。nginx一般是把请求发fastcgi管理进程处理，fascgi管理进程选择cgi子进程处理结果并返回给nginx. php-fpm是一个php fastcgi管理器, 目前直接集成在php中.</p>
<p>安装php:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">sudo apt install php</span><br><span class="line">sudo systemctl restart php7.0-fpm.service</span><br></pre></td></tr></table></figure>

<p>nginx配置:</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="section">server</span> &#123;</span><br><span class="line">        <span class="attribute">listen</span> <span class="number">80</span>;</span><br><span class="line">        <span class="attribute">server_name</span> <span class="regexp">*.liuvv.com</span>;</span><br><span class="line">        <span class="attribute">root</span> /home/levonfly/www;</span><br><span class="line">        <span class="attribute">index</span> index.php index.html index.htm;</span><br><span class="line">  </span><br><span class="line">        <span class="attribute">location</span> <span class="regexp">~* \.php$</span> &#123;</span><br><span class="line">                <span class="attribute">fastcgi_pass</span> unix:/run/php/php7.0-fpm.sock;</span><br><span class="line">                <span class="attribute">include</span>         fastcgi_params;</span><br><span class="line">                <span class="attribute">fastcgi_param</span>   SCRIPT_FILENAME    <span class="variable">$document_root</span><span class="variable">$fastcgi_script_name</span>;</span><br><span class="line">                <span class="attribute">fastcgi_param</span>   SCRIPT_NAME        <span class="variable">$fastcgi_script_name</span>;</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="4-3-虚拟主机配置"><a href="#4-3-虚拟主机配置" class="headerlink" title="4.3 虚拟主机配置"></a>4.3 虚拟主机配置</h3><p>nginx 使用域名，主要是使用<code>server</code>模块下的<code>server_name</code>选项。</p>
<p>参考: <a href="http://www.liuvv.com/p/d039.html" target="_blank" rel="noopener">http://www.liuvv.com/p/d039.html</a></p>
<h3 id="4-4-URL路由重写"><a href="#4-4-URL路由重写" class="headerlink" title="4.4 URL路由重写"></a>4.4 URL路由重写</h3><p>nginx 使用url 重写，主要是使用<code>server</code>模块下的<code>location</code>模块。</p>
<p>参考: <a href="http://www.liuvv.com/p/51e59d76.html" target="_blank" rel="noopener">http://www.liuvv.com/p/51e59d76.html</a></p>
<h3 id="4-5-反向代理配置"><a href="#4-5-反向代理配置" class="headerlink" title="4.5 反向代理配置"></a>4.5 反向代理配置</h3><p>nginx 使用反向代理，主要是使用 <code>server</code>模块下 <code>location</code>模块下的<code>proxy_pass</code>选项。</p>
<p>参考: <a href="http://www.liuvv.com/p/51e59d76.html" target="_blank" rel="noopener">http://www.liuvv.com/p/51e59d76.html</a></p>
<h3 id="4-6-负载均衡配置"><a href="#4-6-负载均衡配置" class="headerlink" title="4.6 负载均衡配置"></a>4.6 负载均衡配置</h3><p>nginx 使用反向代理，主要是使用<code>upstream</code>模块(和server 平级)。</p>
<p>参考: <a href="https://www.liuvv.com/p/4c38afcc.html" target="_blank" rel="noopener">https://www.liuvv.com/p/4c38afcc.html</a></p>
<h1 id="五-参考资料"><a href="#五-参考资料" class="headerlink" title="五. 参考资料"></a>五. 参考资料</h1><ul>
<li><p>nginx的配置、虚拟主机、负载均衡和反向代理</p>
<p><a href="https://www.zybuluo.com/phper/note/89391" target="_blank" rel="noopener">https://www.zybuluo.com/phper/note/89391</a>  </p>
<p><a href="https://www.zybuluo.com/phper/note/90310" target="_blank" rel="noopener">https://www.zybuluo.com/phper/note/90310</a>  </p>
<p><a href="https://www.zybuluo.com/phper/note/133244" target="_blank" rel="noopener">https://www.zybuluo.com/phper/note/133244</a>  </p>
</li>
<li><p>nginx 配置详解</p>
<p><a href="https://my.oschina.net/duxuefeng/blog/34880" target="_blank" rel="noopener">https://my.oschina.net/duxuefeng/blog/34880</a></p>
<p><a href="http://www.nginx.cn/591.html" target="_blank" rel="noopener">http://www.nginx.cn/591.html</a> </p>
<p><a href="https://jkzhao.github.io/2018/01/23/Nginx%E9%85%8D%E7%BD%AE%E8%AF%A6%E8%A7%A3%E5%8F%8A%E4%BC%98%E5%8C%96" target="_blank" rel="noopener">https://jkzhao.github.io/2018/01/23/Nginx%E9%85%8D%E7%BD%AE%E8%AF%A6%E8%A7%A3%E5%8F%8A%E4%BC%98%E5%8C%96</a> </p>
<p><a href="https://www.kancloud.cn/curder/nginx/96672" target="_blank" rel="noopener">https://www.kancloud.cn/curder/nginx/96672</a> </p>
</li>
<li><p>在线生成nginx 配置</p>
<p> <a href="https://nginxconfig.io" target="_blank" rel="noopener">https://nginxconfig.io</a></p>
</li>
<li><p>nginx 优秀教程</p>
<p> <a href="https://xuexb.github.io/learn-nginx/example/" target="_blank" rel="noopener">https://xuexb.github.io/learn-nginx/example/</a>  </p>
<p> <a href="https://www.kancloud.cn/hfpp2012/nginx-tutorial/467009" target="_blank" rel="noopener">https://www.kancloud.cn/hfpp2012/nginx-tutorial/467009</a></p>
</li>
</ul>

    </div>

    
    
    
        
      
        <div id="reward-container">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作, 一个耿直的笑脸~</div>
  <button id="reward-button" disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
        
      
      <div style="display: inline-block">
        <img src="/images/wechatpay.jpg" alt="Levon 微信支付">
        <p>微信支付</p>
      </div>
        
      
      <div style="display: inline-block">
        <img src="/images/alipay.jpg" alt="Levon 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

      

      <footer class="post-footer">
          
            
          
          <div class="post-tags">
            
              <a href="/tags/linux/" rel="tag"># linux</a>
            
              <a href="/tags/nginx/" rel="tag"># nginx</a>
            
          </div>
        

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
              
                <a href="/p/4c38afcc.html" rel="next" title="nginx通过upstream实现负载均衡">
                  <i class="fa fa-chevron-left"></i> nginx通过upstream实现负载均衡
                </a>
              
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
              
                <a href="/p/51e59d76.html" rel="prev" title="nginx的location用法和rewrite规则">
                  nginx的location用法和rewrite规则 <i class="fa fa-chevron-right"></i>
                </a>
              
            </div>
          </div>
        
      </footer>
    
  </div>
  
  
  
  </article>

  </div>


          </div>
          
    
    
  <div class="comments" id="comments">
    <div id="disqus_thread">
      <noscript>Please enable JavaScript to view the comments powered by Disqus.</noscript>
    </div>
  </div>
  
  

        </div>
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">
        
        
        
        
      

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#零-前言"><span class="nav-number">1.</span> <span class="nav-text">零. 前言</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#0-1-配置文件在哪"><span class="nav-number">1.0.1.</span> <span class="nav-text">0.1 配置文件在哪</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#0-2-默认root在哪"><span class="nav-number">1.0.2.</span> <span class="nav-text">0.2 默认root在哪</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#0-3-重启nginx"><span class="nav-number">1.0.3.</span> <span class="nav-text">0.3 重启nginx</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#一-nginx-常用功能说明"><span class="nav-number">2.</span> <span class="nav-text">一. nginx 常用功能说明</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-反向代理"><span class="nav-number">2.0.1.</span> <span class="nav-text">1.1 反向代理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-负载均衡"><span class="nav-number">2.0.2.</span> <span class="nav-text">1.2 负载均衡</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-web缓存"><span class="nav-number">2.0.3.</span> <span class="nav-text">1.3 web缓存</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#二-nginx配置文件结构"><span class="nav-number">3.</span> <span class="nav-text">二. nginx配置文件结构</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-配置文件结构"><span class="nav-number">3.0.1.</span> <span class="nav-text">2.1 配置文件结构</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#三-模块配置说明"><span class="nav-number">4.</span> <span class="nav-text">三. 模块配置说明</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-main模块"><span class="nav-number">4.0.1.</span> <span class="nav-text">3.1 main模块</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-events-模块"><span class="nav-number">4.0.2.</span> <span class="nav-text">3.2 events 模块</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-3-http-模块"><span class="nav-number">4.0.3.</span> <span class="nav-text">3.3 http 模块</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-4-server-模块-http的子模块-虚拟主机"><span class="nav-number">4.0.4.</span> <span class="nav-text">3.4 server 模块 (http的子模块, 虚拟主机)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-5-location-模块-server的子模块-重要"><span class="nav-number">4.0.5.</span> <span class="nav-text">3.5 location 模块(server的子模块, 重要)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-6-upstream-模块-http子模块"><span class="nav-number">4.0.6.</span> <span class="nav-text">3.6 upstream 模块(http子模块)</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#四-nginx-配置实战"><span class="nav-number">5.</span> <span class="nav-text">四. nginx 配置实战</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-1-nginx指令"><span class="nav-number">5.0.1.</span> <span class="nav-text">4.1 nginx指令</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2-nginx-快速配置教程"><span class="nav-number">5.0.2.</span> <span class="nav-text">4.2 nginx 快速配置教程</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#4-2-1-如果有多个location模块-匹配最长的"><span class="nav-number">5.0.2.0.1.</span> <span class="nav-text">4.2.1 如果有多个location模块, 匹配最长的</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#4-2-2-一个nginx实例可以通过listen监听不同端口"><span class="nav-number">5.0.2.0.2.</span> <span class="nav-text">4.2.2 一个nginx实例可以通过listen监听不同端口</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#4-2-3-fastcgi方式"><span class="nav-number">5.0.2.0.3.</span> <span class="nav-text">4.2.3 fastcgi方式</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-3-虚拟主机配置"><span class="nav-number">5.0.3.</span> <span class="nav-text">4.3 虚拟主机配置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-4-URL路由重写"><span class="nav-number">5.0.4.</span> <span class="nav-text">4.4 URL路由重写</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-5-反向代理配置"><span class="nav-number">5.0.5.</span> <span class="nav-text">4.5 反向代理配置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-6-负载均衡配置"><span class="nav-number">5.0.6.</span> <span class="nav-text">4.6 负载均衡配置</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#五-参考资料"><span class="nav-number">6.</span> <span class="nav-text">五. 参考资料</span></a></li></ol></div>
        
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image"
      src="/images/avatar.jpg"
      alt="Levon">
  <p class="site-author-name" itemprop="name">Levon</p>
  <div class="site-description" itemprop="description">Never Give Up</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">127</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-categories">
        
          
            <a href="/categories/">
          
        
        <span class="site-state-item-count">34</span>
        <span class="site-state-item-name">分类</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-tags">
        
          
            <a href="/tags/">
          
        
        <span class="site-state-item-count">76</span>
        <span class="site-state-item-name">标签</span>
        </a>
      </div>
    
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://github.com/unix2dos" title="GitHub &rarr; https://github.com/unix2dos" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="mailto:levonfly@gmail.com" title="E-Mail &rarr; mailto:levonfly@gmail.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://twitter.com/levonfly" title="Twitter &rarr; https://twitter.com/levonfly" rel="noopener" target="_blank"><i class="fa fa-fw fa-twitter"></i>Twitter</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://weibo.com/l6241425" title="Weibo &rarr; https://weibo.com/l6241425" rel="noopener" target="_blank"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
      </span>
    
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Levon</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    <span title="站点总字数">507k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">7:41</span>
</div>

        












        
      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js?v=3.1.0"></script>
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script src="/js/utils.js?v=7.4.0"></script><script src="/js/motion.js?v=7.4.0"></script>
<script src="/js/schemes/pisces.js?v=7.4.0"></script>

<script src="/js/next-boot.js?v=7.4.0"></script>



  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>








  <script src="/js/local-search.js?v=7.4.0"></script>














  

  

  

<script>
  function loadCount() {
    var d = document, s = d.createElement('script');
    s.src = 'https://levonfly.disqus.com/count.js';
    s.id = 'dsq-count-scr';
    (d.head || d.body).appendChild(s);
  }
  // defer loading until the whole page loading is completed
  window.addEventListener('load', loadCount, false);
</script>
<script>
  function disqus_config() {
    this.page.url = "https://unix2dos.github.io/p/7245bfc7.html";
    this.page.identifier = "p/7245bfc7.html";
    this.page.title = 'nginx介绍和常用模块配置';};
  function loadComments() {
    if (window.DISQUS) {
      DISQUS.reset({
        reload: true,
        config: disqus_config
      });
    } else {
      var d = document, s = d.createElement('script');
      s.src = 'https://levonfly.disqus.com/embed.js';
      s.setAttribute('data-timestamp', '' + +new Date());
      (d.head || d.body).appendChild(s);
    }
  }
    window.addEventListener('load', loadComments, false);
  
</script>

</body>
</html>
